﻿using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using Usido.CRM.Core.Extensions;
using Usido.CRM.Dto;
using Usido.CRM.IRepository;
using Usido.CRM.Models;
using Usido.CRM.Repository;

namespace Usido.CRM.App.Forms
{
    public partial class 药品价格设置界面 : Form
    {
        private readonly ISysProductRepository ProductReposioty = new SysProductRepository();

        //错误日志
        private readonly ILog logger = LogManager.GetLogger(typeof(药品价格设置界面));

        //操作日志
        private readonly ISysLogRepository LogReposioty = new SysLogRepository();

        private readonly string UserId = "";

        public 药品价格设置界面(string userId)
        {
            this.UserId = userId;
            InitializeComponent();
        }

        #region 窗体绘制

        /// <summary>
        /// 解决加载窗体多控件所造成的闪烁
        /// </summary>
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x02000000;
                return cp;
            }
        }

        #endregion 窗体绘制

        private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
        }



       public void BindData(string where)
        {
            var productList = ProductReposioty.GetProductList(where);
            dataGridView1.AutoGenerateColumns = false;
            dataGridView1.DataSource = productList;
        }

        private void 药品价格设置界面_Load(object sender, EventArgs e)
        {
            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            BindData("");
        }

        private void toolStripDropDownButton1_Click(object sender, EventArgs e)
        {
            txtDW.Text = "";
            txtLSDW.Text = "";
            txtSCQY.Text = "";
            txtYHJ.Text = "";
            txtYPBM.Text = "";
            txtYPGG.Text = "";
            txtYPMC.Text = "";
            txtLSDW.Text = "";
            txtYHJ.Text = "100";

            this.tabControl1.SelectedIndex = 1;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                string Id = dataGridView1.SelectedRows[0].Cells["药品编号"].Value.ToString();
                if (string.IsNullOrEmpty(txtLSDW.Text.Trim()) || string.IsNullOrEmpty(txtYHJ.Text.Trim()))
                {
                    MessageBox.Show("请输入销售单价");
                }
                if (ProductReposioty.UpdatePrice(Convert.ToInt32(Id), Convert.ToDecimal(txtLSDW.Text.Trim()), Convert.ToDecimal(txtYHJ.Text.Trim())))
                {
                    LogReposioty.AddLog(Convert.ToInt32(UserId), "药品单价设置成功");
                    MessageBox.Show("单价设置成功");
                    this.tabControl1.SelectedIndex = 0;
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }
        }

        private void dataGridView1_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                txtLSDW.Text = "";
                string Id = dataGridView1.SelectedRows[0].Cells["药品编号"].Value.ToString();
                SysProduct m = ProductReposioty.Get(Convert.ToInt32(Id));
                txtSCQY.Text = m.ManufacturingEnterprise;
                txtDW.Text = m.MarketingUnit;
                txtYPBM.Text = m.Id.ToString();
                txtYPMC.Text = m.ProductName;
                txtYPGG.Text = m.Specification;
                txtLSDW.Text = m.RetailPrice.ToString();
                txtYHJ.Text = m.MemberDiscount.ToString();
                this.tabControl1.SelectedIndex = 1;
            }
            catch (Exception ex)
            {
                MessageBox.Show("请选择药品!");
            }
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            string seacher = textBox1.Text.Trim();
            BindData($" ProductCode like '%{seacher}%'  or ProductName like '%{seacher}%'  ");
        }

        private void toolStripDropDownButton2_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void toolStripDropDownButton3_Click(object sender, EventArgs e)
        {
            try
            {
                string Id = dataGridView1.SelectedRows[0].Cells["药品编号"].Value.ToString();

                var model = ProductReposioty.Get(Id.ToInt());
                txtYPBM.Text = model.Id.ToString();
                txtYPMC.Text = model.ProductName;
                txtSCQY.Text = model.ManufacturingEnterprise;
                txtYPGG.Text = model.Specification;
                txtDW.Text = model.MarketingUnit;
                txtLSDW.Text = model.RetailPrice.ToString();
                txtYHJ.Text = model.MemberDiscount.ToString();
                this.tabControl1.SelectedIndex = 1;
            }
            catch (Exception ex)
            {
                MessageBox.Show("请选择药品!");
            }
        }

        private void dataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            DataGridView dgv = sender as DataGridView;
            if (dgv.Columns[e.ColumnIndex].SortMode == DataGridViewColumnSortMode.Programmatic)
            {
                string columnBindingName = dgv.Columns[e.ColumnIndex].DataPropertyName;
                switch (dgv.Columns[e.ColumnIndex].HeaderCell.SortGlyphDirection)
                {
                    case System.Windows.Forms.SortOrder.None:
                    case System.Windows.Forms.SortOrder.Ascending:
                        CustomSort(columnBindingName, "desc");
                        dgv.Columns[e.ColumnIndex].HeaderCell.SortGlyphDirection = System.Windows.Forms.SortOrder.Descending;
                        break;
                    case System.Windows.Forms.SortOrder.Descending:
                        CustomSort(columnBindingName, "asc");
                        dgv.Columns[e.ColumnIndex].HeaderCell.SortGlyphDirection = System.Windows.Forms.SortOrder.Ascending;
                        break;
                }
            }
        }



        /// <summary>
        /// 自定义排序
        /// </summary>
        /// <param name="columnName">绑定的字段名</param>
        /// <param name="sortMode">排序方式 asc 升序 desc 降序</param>
        private void CustomSort(string columnBindingName, string sortMode)
        {
            if (columnBindingName == "RetailPrice")
            {
                var list = this.dataGridView1.DataSource as List<SysProductDto>;
                if (sortMode == "asc")
                {
                    var newList = list.OrderBy(m => m.RetailPrice).ToList();
                    dataGridView1.DataSource = newList;
                }
                else
                {
                    var newList = list.OrderByDescending(m => m.RetailPrice).ToList();
                    dataGridView1.DataSource = newList;
                }
            }
            this.dataGridView1.Refresh();
        }
    }
}